package com.neusoft.nep.SystemAdminstrator.Controller;

import com.neusoft.nep.GridOfficer.controller.GirdOfficerLoginViewController;
import com.neusoft.nep.GridOfficer.entity.Officer;
import com.neusoft.nep.SystemAdminstrator.Common.AlertUtills;
import com.neusoft.nep.SystemAdminstrator.Common.FileUtills;
import com.neusoft.nep.SystemAdminstrator.entity.SystemFeedback;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class DifferentGridName {
    private int keyID;
    private String GridName;

    public int getKeyID() {
        return keyID;
    }

    public void setKeyID(int keyID) {
        this.keyID = keyID;
    }

    public String getGridName() {
        return GridName;
    }

    public void setGridName(String gridName) {
        GridName = gridName;
    }
}

public class PublicDataAssignDifferentController {
    private int i = 0;
    private List<String> assignedOfficerNames = new ArrayList<>();
    AlertUtills alertUtills = new AlertUtills();
    @FXML
    private ComboBox<String> comName;
    Map<String, Officer> officerMap = FileUtills.readMapObject("GirdOfficer.txt");

    @FXML
    private ComboBox<String> comProv, comCity;
    Map<String, List<String>> provinceMap = new HashMap<>();

    @FXML
    private Button btn_DAssign;

    public void DifferentAssign(ActionEvent event) throws IOException {
        String aaa = comName.getSelectionModel().getSelectedItem().toString();
        System.out.println(aaa);
        File newfile = new File(aaa + ".txt");

        try {
            newfile.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (newfile.exists()) {
            if (i != 0) {
                i = 0;
            }
            GirdOfficerLoginViewController.setOfficerName(aaa);
            alertUtills.Showdialog("指派", null, "指派成功");
            systemFeedback.setAssigned(true);
            Map<String, SystemFeedback> systemFeedbackMap = new HashMap<>();
            systemFeedbackMap.put(String.valueOf(systemFeedback.getIndex()), systemFeedback);
            FileUtills.writeMapObject(aaa + ".txt", systemFeedbackMap);
            Map<String, SystemFeedback> systemFeedbackMap1 = FileUtills.readMapObject("SystemFeedback.txt");
            systemFeedbackMap1.put(String.valueOf(systemFeedback.getIndex()), systemFeedback);
            FileUtills.writeMapObject("SystemFeedback.txt", systemFeedbackMap1);
            System.out.println(systemFeedback.getAqiLevel());

            // 将指派的网格员名字添加到集合中
            if (!assignedOfficerNames.contains(aaa)) {
                assignedOfficerNames.add(aaa);
                // 将集合保存到文件中
                FileUtills.writeListObject("AssignofficerNames.txt", assignedOfficerNames);
            }

            i++;
        } else {
            alertUtills.ShowErrorDialog("指派", null, "指派失败！");
        }
    }

    public void initialize() {
        labID.setText("系统管理员：" + loginController.currentLoginID);

        // 从文件中读取已指派的网格员名字
        assignedOfficerNames = FileUtills.readListObject("AssignofficerNames.txt");
        if (assignedOfficerNames == null) {
            assignedOfficerNames = new ArrayList<>();
        }

        // ========== 1. 加载省份（从 officerMap 动态提取） ==========
        List<String> provinces = officerMap.values().stream()
                .map(Officer::getProvince)   // 提取省份
                .distinct()                  // 去重
                .collect(Collectors.toList()); // 转 List
        comProv.setItems(FXCollections.observableArrayList(provinces));

        // ========== 2. 省份变化 → 加载对应城市 ==========
        comProv.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal == null) { // 省份未选择时，清空城市和指派对象
                comCity.setItems(FXCollections.observableArrayList());
                comName.setItems(FXCollections.observableArrayList());
                return;
            }
            // 提取当前省份下的所有城市（去重）
            List<String> cities = officerMap.values().stream()
                    .filter(o -> o.getProvince().equals(newVal))
                    .map(Officer::getCity)
                    .distinct()
                    .collect(Collectors.toList());
            comCity.setItems(FXCollections.observableArrayList(cities));
            comCity.setPromptText("请选择城市");
            comCity.getSelectionModel().clearSelection(); // 清空城市选择
        });

        // ========== 3. 城市变化 → 加载对应指派对象（Officer 姓名） ==========
        comCity.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal) -> {
            String province = comProv.getValue(); // 当前选中的省份
            if (province == null || newVal == null) { // 省份或城市未选择时，清空指派对象
                comName.setItems(FXCollections.observableArrayList());
                return;
            }
            // 提取当前城市下的所有 Officer 姓名（去重）
            List<String> officerNames = officerMap.values().stream()
                    .filter(o -> o.getProvince().equals(province)
                            && o.getCity().equals(newVal))
                    .map(Officer::getName)
                    .collect(Collectors.toList());
            comName.setItems(FXCollections.observableArrayList(officerNames));
        });
    }

    @FXML
    private Label labID;
    SystemFeedback systemFeedback;
    private void initDataToUI() {
        if (systemFeedback != null) {
            infoIdValue.setText(String.valueOf(systemFeedback.getIndex()));
            feedbackPersonValue.setText(systemFeedback.getName() + " " + systemFeedback.getSex() + " " + systemFeedback.getBirthday());
            phoneValue.setText(systemFeedback.getPhoneNumber());
            addressValue.setText(systemFeedback.getAddress());
            descriptionValue.setText(systemFeedback.getDescription());
            levelValue.setText(systemFeedback.getAqiLevel());
            feedbackTimeValue.setText(systemFeedback.getTime());
        }
    }
    public void setSystemFeedback(SystemFeedback systemFeedback) {
        this.systemFeedback = systemFeedback;
        initDataToUI();
    }

    @FXML
    private Label infoIdValue;
    @FXML
    private Label feedbackPersonValue;
    @FXML
    private Label phoneValue;
    @FXML
    private Label addressValue;
    @FXML
    private Label descriptionValue;
    @FXML
    private Label levelValue;
    @FXML
    private Label feedbackTimeValue;

    @FXML
    private Button btn_out;

    public void OUT(ActionEvent actionEvent) {
        System.exit(0);
    }

    @FXML
    private Button btn_back;

    public void toback(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../View/PublicDataAssign.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_back.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }

    @FXML
    private MenuItem mi_PSL;

    public void PSLClick(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../View/publicList.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }

    @FXML
    private MenuItem mi_AQI;

    public void AQIListClick(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../View/AQImakesure.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }

    @FXML
    private MenuItem mi_PGC;

    public void PGCClick(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../View/ProvincialGroupComponentItemInspectionStatistics.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }

    @FXML
    private MenuItem mi_AqiDistribute;

    public void AqiDistributeClick(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../View/AqiDistributeTotalStatisView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }

    @FXML
    private MenuItem mi_Other;

    public void OtherClick(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../View/OtherTotalStatisView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }

    @FXML
    private MenuItem mi_AqiTrendTotal;

    public void AqiTrendClick(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../View/AqiTrendTotalStatisView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_out.getScene();
        scene.setRoot(root);
        Stage stage = (Stage) scene.getWindow();
        stage.show();
    }
}